package com.white.seckill;

import com.alibaba.fastjson.JSONObject;

import java.util.HashMap;
import java.util.Map;
import java.util.Objects;

/**
 * <p>
 * 九价秒杀
 * </p>
 *
 * @author white
 * @since 2022/4/6
 */
public class Spike implements Runnable{

    /**
     * 秒杀类型
     */
    private final String marketingType;

    /**
     * 秒杀ID
     */
    private String marketingId;

    /**
     * 商品ID
     */
    private final String productId;

    /**
     * 接种人身份证号码
     */
    private final String idNo;

    /**
     * 接种人名称
     */
    private final String name;

    /**
     * 接种人手机号
     */
    private final String phoneNo;

    /**
     * 当前用户的cookie
     */
    private final String cookie;

    public Spike(String marketingType, String marketingId, String productId, String idNo, String name, String phoneNo, String cookie) {
        this.marketingType = marketingType;
        this.marketingId = marketingId;
        this.productId = productId;
        this.idNo = idNo;
        this.name = name;
        this.phoneNo = phoneNo;
        this.cookie = cookie;
    }

    @Override
    public void run() {
        //获取秒杀ID
        if (marketingId == null) {
            do {
                Result<String> idResult = getMarketingId();
                if (!idResult.isSuccess()) {
                    System.out.println("秒杀ID获取失败");
                    try {
                        Thread.sleep(500);
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                }else {
                    marketingId = idResult.getData();
                }
            } while (marketingId == null);
        }
        Result<String> order = createOrder();
        if (!order.isSuccess()) {
            throw new RuntimeException("请求失败"+ order.getMsg());
        }
        Result<?> result = setReceiver(order.getData());
        if (!result.isSuccess()) {
            throw new RuntimeException("请求失败"+ result.getMsg());
        }
        result = setIdNo(order.getData());
        if (!result.isSuccess()) {
            throw new RuntimeException("请求失败"+ result.getMsg());
        }
        result = apply(order.getData());
        if (!result.isSuccess()) {
            throw new RuntimeException("请求失败"+ result.getMsg());
        }
        System.out.println("秒杀成功,请前往我的订单付款");
    }

    /**
     * 构建请求头
     * @return
     */
    private Map<String,String> buildHeaders(){
        Map<String,String> headers = new HashMap<>();
        headers.put("Content-Type","application/x-www-form-urlencoded");
        headers.put("Host","wx7.jzapp.fkw.com");
        headers.put("User-Agent","Mozilla/5.0 (iPhone; CPU iPhone OS 13_7 like Mac OS X) AppleWebKit/605.1.15 (KHTML, like Gecko) Mobile/15E148 MicroMessenger/8.0.18(0x1800123c) NetType/WIFI Language/zh_CN");
        headers.put("Referer","https://servicewechat.com/wx8e237ddfbc2c3e99/2/page-frame.html");
        headers.put("Cookie",cookie);
        return headers;
    }

    /**
     * 模拟用户操作创建一个秒杀订单
     *
     * @return 返回秒杀订单号 preOrderId
     */
    private Result<String> createOrder(){
        //请求头
        Map<String, String> headers = buildHeaders();
        //构建请求体
        Map<String, Object> body = new HashMap<>();
        body.put("pdInfoList","[]");
        body.put("marketingType",marketingType);
        body.put("marketingId",marketingId);
        body.put("marketingDetailId","0");
        body.put("fromDetail",true);
        body.put("optionList","[]");
        body.put("amount",1);
        body.put("productId",productId);
        //请求
        String post = HttpUtils.post("https://wx7.jzapp.fkw.com/28359275/0/mstl_h.jsp?cmd=setWafCk_addImmePreOrder",
                body, headers,
                3000,
                3000,
                "UTF-8");
        //解析结果
        Map map = JSONObject.parseObject(post, Map.class);
        if (map.get("rt") != null && Objects.equals(0,map.get("rt"))){
            return Result.success(String.valueOf(map.get("preOrderId")));
        }
        return Result.fail(String.valueOf(map.get("msg")));
    }

    /**
     * 对秒杀订单的收货人进行设置
     * @param preOrderId 模拟用户操作创建一个秒杀订单执行后的结果ID
     */
    private Result<?> setReceiver(String preOrderId){
        //请求头
        Map<String, String> headers = buildHeaders();
        //构建请求体
        Map<String, Object> body = new HashMap<>();
        body.put("preOrderId",preOrderId);
        body.put("batchDeliveryList","[{\"preOrderId\":"+preOrderId+",\"selfRaisingMemberInfo\":{\"name\":\""+name+"\",\"mobile\":\""+phoneNo+"\"},\"mctId\":0,\"shipType\":\"\",\"shipSort\":8,\"deliveryStyle\":2,\"selfRaisingPoint\":{\"aid\":28359275,\"wid\":0,\"name\":\"重庆明好医院\",\"picList\":[],\"contact\":\"客服\",\"contactNum\":\"17320425142\",\"flag\":0,\"setting\":{\"loc\":{\"ai\":{\"prc\":\"500000\",\"cic\":\"500100\",\"coc\":\"500107\",\"sta\":\"重庆明好医院\"},\"as\":\"重庆重庆市九龙坡区重庆明好医院\",\"pp\":{\"lng\":106.260422,\"lat\":29.289093,\"pt\":1}},\"bus\":{\"redl\":[{\"sth\":9,\"stm\":0,\"eth\":18,\"etm\":0,\"etind\":false}],\"rewl\":[]}},\"id\":1,\"mai\":1,\"rai\":{\"prc\":\"500000\",\"cic\":\"500100\",\"coc\":\"500107\",\"sta\":\"重庆明好医院\"},\"ais\":\"重庆重庆市九龙坡区重庆明好医院\",\"phone\":\"17320425142\",\"pp\":{\"lng\":106.260422,\"lat\":29.289093,\"pt\":1},\"idm\":false}}]");
        //请求
        String post = HttpUtils.post("https://wx7.jzapp.fkw.com/28359275/0/mstl_h.jsp?cmd=setWafCk_batchSetDeliveryService",
                body, headers,
                3000,
                3000,
                "UTF-8");
        //解析结果
        Map map = JSONObject.parseObject(post, Map.class);
        if (map.get("rt") != null && Objects.equals(0,map.get("rt"))){
            return Result.success();
        }
        return Result.fail(String.valueOf(map.get("msg")));
    }

    /**
     * 对秒杀订单的备注信息进行设置（在此设置身份证号）
     * @param preOrderId 模拟用户操作创建一个秒杀订单执行后的结果ID
     */
    private Result<?> setIdNo(String preOrderId){
        //请求头
        Map<String, String> headers = buildHeaders();
        //构建请求体
        Map<String, Object> body = new HashMap<>();
        body.put("preOrderId",preOrderId);
        body.put("mctId",0);
        body.put("remark",idNo);
        //请求
        String post = HttpUtils.post("https://wx7.jzapp.fkw.com/28359275/0/mstl_h.jsp?cmd=setWafCk_setRemarkService",
                body, headers,
                3000,
                3000,
                "UTF-8");
        //解析结果
        Map map = JSONObject.parseObject(post, Map.class);
        if (map.get("rt") != null && Objects.equals(0,map.get("rt"))){
            return Result.success();
        }
        return Result.fail(String.valueOf(map.get("msg")));
    }

    /**
     * 申请下单 秒杀
     * @param preOrderId
     * @return
     */
    private Result<?> apply(String preOrderId){
        //请求头
        Map<String, String> headers = buildHeaders();
        //构建请求体
        Map<String, Object> body = new HashMap<>();
        body.put("preOrderId",preOrderId);
        //请求
        String post = HttpUtils.post("https://wx7.jzapp.fkw.com/28359275/0/mstl_h.jsp?cmd=setWafCk_settleOrder",
                body, headers,
                3000,
                3000,
                "UTF-8");
        //解析结果
        Map map = JSONObject.parseObject(post, Map.class);
        if (map.get("rt") != null && Objects.equals(0,map.get("rt"))){
            return Result.success();
        }
        return Result.fail(String.valueOf(map.get("msg")));
    }

    /**
     * 获取秒杀ID
     * @return
     */
    private Result<String> getMarketingId(){
        //请求头
        Map<String, String> headers = buildHeaders();
        //请求
        String post = HttpUtils.post("https://wx7.jzapp.fkw.com/28359275/0/wxmallapp_h.jsp?cmd=getProductDetailPage&isFromPd=true&pid="+productId+"&pageNo=1&lng=&lat=&addrInfo={%22prc%22:%22%22,%22cic%22:%22%22,%22coc%22:%22%22}&merchantId=0&selfTakeId=0",
                new HashMap<>(), headers,
                3000,
                3000,
                "UTF-8");
        //解析结果
        Map<?,?> map = JSONObject.parseObject(post, Map.class);
        if (map.get("rt") != null && Objects.equals(0,map.get("rt"))){
            Map<?,?> data = (Map<?,?>) map.get("rtData");
            if (data != null && data.containsKey("secKillInfo")) {
                //获取内部的秒杀ID
                return Result.success(String.valueOf(((Map<?,?>) data.get("secKillInfo")).get("id")));
            }
        }
        return Result.fail(String.valueOf(map.get("msg")));
    }

}
